import requests
import json
from ioutil import Writer


def getAuthor(file_path, url):
    # url = 'https://api.github.com/repos/scala/scala/commits'
    headers = {'User-Agent': 'Mozilla/5.0',
               'Authorization': 'token 2c981cb9909e55928477329057be76ef35453b47',
               'Content-Type': 'application/json',
               'Accept': 'application/json'
               }
    resp = requests.get(url, params={'path': file_path}, headers=headers)
    commits = json.loads(resp.content)
    last_commit = commits[-1]
    last_author=last_commit['commit']['author']['name']
    authors = ""
    for commit in commits:
        try:
            authors = authors + commit['commit']['author']['name'] + ", "
        except Exception:
            authors = authors + 'None' + ", "
    return authors, last_author


def getAllpath(infile, project):
    paths = []
    f = open(infile, 'r')
    sourceInline = f.readlines()
    for line in sourceInline:
        paths.append(line.split('scala_project\\' + project + '\\')[1][:-1].replace('\\', '/'))
    return paths


if __name__ == '__main__':
    paths = getAllpath('high_path.txt', 'sbt')
    authors = ""
    last_authors = ""
    i = 1
    for path in paths:
        author, last_author = getAuthor(path, 'https://api.github.com/repos/sbt/sbt/commits')
        authors = authors + author.encode('utf-8') + "\n"
        last_authors = last_authors + last_author.encode('utf-8') + "\n"
        print i
        i = i + 1

    with Writer("authors.txt", encoding='utf8') as writer:
        writer.write(authors)

    with Writer("last_authors.txt", encoding='utf8') as writer:
        writer.write(last_authors)
